<template>
  <div class="add-product-wrapper">
    <el-form label-width="108px" :model="form" ref="form" :rules="rules">
      <el-card style="margin: 20px 20px; font-size: 14px">
        <div slot="header">
          <span>基本信息</span>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="outProductId">
              <el-input v-model="form.outProductId" placeholder="请输入商品编码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="品牌" prop="brandId">
              <brand-select v-model="form.brandId" @change="onBrandChange"></brand-select>
            </el-form-item>
          </el-col> -->

          <el-col :span="8">
            <el-form-item label="分类" prop="categoryId">
              <product-category-select v-model="form.categoryId" @change="categoryChange"></product-category-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上架状态">
              <DictRadio v-model="form.publishStatus" size="small"
                        :radioData="dict.type.pms_publish_status"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="母价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入PRICE"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位"></el-input>
            </el-form-item>
          </el-col>
         <el-col :span="8">
           <el-form-item label="库存" prop="totalNum">
             <el-input v-model="form.totalNum" placeholder="商品库存"></el-input>
           </el-form-item>
         </el-col>
        </el-row>
      </el-card>

      <el-card style="margin: 20px 20px; font-size: 14px">
        <div slot="header">
          <span>产品图片</span>
        </div>
        <el-form-item label="主图" prop="pic">
          <oss-image-upload v-model="form.pic" :limit="1"></oss-image-upload>
        </el-form-item>
      </el-card>

      <el-card style="margin: 20px 20px; font-size: 14px">
        <div slot="header">
          <span>子产品</span>
        </div>
        <div class="skus">
          <p class="skus-label">子产品图片</p>
          <div class="sku-wrapper">
            <div class="sku_sorts">
              <div class="sku_sort" v-for="(s, idx0) in form.productChildList" :key="idx0">
                <el-form-item label-width="0" :prop="'productChildList.'+idx0+'.pic'" :rules="{required: true, message: '请上传图片', trigger: ['blur', 'change']}">
                  <div class="label flex-center">
                      <oss-image-upload v-model="s.pic" :limit="1"></oss-image-upload>
                    <el-button class="red" @click="deleteSkuSort(idx0)">-删除子产品</el-button>
                  </div>
                </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label-width="60px" label="名称" :prop="'productChildList.'+idx0+'.name'"  :rules="{required: true, message: '名称不能为空', trigger: 'blur'}">
                      <el-input v-model="s.name" placeholder="请输入子产品名称"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label-width="60px" label="编码" :prop="'productChildList.'+idx0+'.outProductId'" :rules="{required: true, message: '编码不能为空', trigger: 'blur'}">
                      <el-input v-model="s.outProductId" placeholder="请输入子产品编码"></el-input>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="8">
                    <el-form-item label-width="0" :prop="'s.'+idx0+'.outProductId'" :rules="{required: true, message: '编码不能为空', trigger: 'blur'}">
                      <el-input v-model="form.outProductId" placeholder="请输入子产品编码"></el-input>
                    </el-form-item>
                  </el-col> -->
                  <el-col :span="8">
                    <el-form-item label-width="60px" label="排序" :prop="'productChildList.'+idx0+'.sort'" :rules="{required: true, message: '排序不能为空', trigger: ['blur', 'change']}">
                      <el-input v-model="s.sort" placeholder="请输入子产品排序"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                     <el-form-item label-width="60px" label="价格" :prop="'productChildList.'+idx0+'.price'" :rules="{required: true, message: '价格不能为空', trigger: 'blur'}">
                       <el-input v-model="s.price" placeholder="请输入PRICE"></el-input>
                     </el-form-item>
                   </el-col>
                   <el-col :span="8">
                     <el-form-item label-width="60px" label="单位" :prop="'productChildList.'+idx0+'.unit'" :rules="{required: true, message: '单位不能为空', trigger: 'blur'}">
                       <el-input v-model="s.unit" placeholder="请输入单位"></el-input>
                     </el-form-item>
                   </el-col>
                  <el-col :span="8">
                    <el-form-item label-width="60px" label="库存" :prop="'productChildList.'+idx0+'.totalNum'" :rules="{required: true, message: '库存不能为空', trigger: 'blur'}">
                      <el-input v-model="s.totalNum" placeholder="商品库存"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <!-- :prop="'productChildList.'+idx0+'.publishStatus'" :rules="{required: true, message: '请选择上架状态', trigger: ['blur', 'change']}" -->
                    <el-form-item label-width="60px" label="状态">
                      <DictRadio v-model="s.publishStatus" size="small"
                                :radioData="dict.type.pms_publish_status"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
            <el-button v-if="form.productChildList.length < 6" @click="addSkuSort">+添加子产品</el-button>
          </div>
        </div>
        <!-- <el-form-item label="子产品图片">
          <div class="sku-wrapper">
            <div class="sku_sorts">
              <div class="sku_sort" v-for="(s, idx0) in form.productChildList" :key="s.name">
                <div class="label flex-center">
                    <oss-image-upload v-model="s.pic" :limit="1"></oss-image-upload>
                  <el-button class="red" @click="deleteSkuSort(idx0)">-删除子产品</el-button>
                </div>
                <div>
                  <el-input v-model="s.name" placeholder="请输入子商品名称"></el-input>
                </div>
                <div>
                  <el-input v-model="s.outProductId" placeholder="请输入子商品编码"></el-input>
                </div>
                <div>
                  <el-input v-model="s.unit" placeholder="请输入单位"></el-input>
                </div>
                <div>
                  <el-input v-model="s.sort" placeholder="请输入排序"></el-input>
                </div>
                <div>
                    <el-input-number v-model="s.price" placeholder="请输入价格">单价：</el-input-number>
                </div>
                <div>
                  <DictRadio v-model="s.publishStatus" size="small"
                            :radioData="dict.type.pms_publish_status"/>
                </div>
                <div style="padding-top: 10px">
                  <el-input-number v-model="s.totalNumber" placeholder="请输入库存数量">库存：</el-input-number>
                </div>
              </div>
            </div>

          </div>
        </el-form-item> -->
        <el-form-item label="子产品列表">
          <!-- <el-button @click="refreshSku()" class="mb20">刷新列表</el-button> -->
          <el-table :data="form.productChildList" :max-height="400">
            <!-- <el-table-column v-for="s in skuAttr" :label="s.name" :key="s.name" :prop="s.name"></el-table-column> -->
            <el-table-column label="展示图片">
              <!-- <template v-slot="{ row }">
                <oss-image-upload class="img-upload-mini" v-model="row.pic" :limit="1" :is-show-tip="false"></oss-image-upload>
              </template> -->
              <template slot-scope="{ row }">
                <el-image v-if="row.pic" :src="row.pic" :preview-src-list="[row.pic]" class="img-upload-mini"/>
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="name"></el-table-column>
            <el-table-column label="编码" prop="outProductId"></el-table-column>
            <el-table-column label="排序" prop="sort"></el-table-column>
            <el-table-column label="价格" prop="price"></el-table-column>
            <el-table-column label="单位" prop="unit"></el-table-column>
            <el-table-column label="库存" prop="totalNum"></el-table-column>
            <el-table-column label="状态" prop="publishStatus">
              <template v-slot="{ row,$index }">
                <p>{{row.publishStatus == '1'?'上架':'下架'}}</p>
              </template>
            </el-table-column>

            <!-- <el-table-column label="销售价格" >
              <template v-slot="{ row,$index }">
                <el-form-item
                  :rules="{ required: true, message: '请填写价格', trigger: 'blur' }"
                  :prop="'skuList['+$index+'].price'">
                  <el-input v-model="row.price"></el-input>
                </el-form-item>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="库存">
              <template v-slot="{ row, $index }">
                <el-input v-model="row.stock" type="number"></el-input>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="编码">
              <template v-slot="{ row }">
                <el-form-item>
                  <el-input v-model="row.outSkuId"></el-input>
                  <el-input v-model="row.spData" v-show="false"></el-input>
                </el-form-item>
              </template>
            </el-table-column> -->
          </el-table>
        </el-form-item>
      </el-card>
      <el-card style="margin: 20px 20px; font-size: 14px">
        <div slot="header">
          <span>详情页</span>
        </div>
        <el-form-item label="商品详情页" prop="detailMobileHtml">
          <Editor v-model="form.detailMobileHtml" placeholder="请输入内容" type="url"></Editor>
        </el-form-item>
      </el-card>

      <div class="tc">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import {addPmsProduct, getPmsProduct, updatePmsProduct} from "@/api/pms/product";
import ProductCategorySelect from "@/views/components/ProductCategorySelect";
import BrandSelect from "@/views/components/BrandSelect";

export default {
  name: "AddProduct",
  dicts: ['pms_publish_status'],
  components: {BrandSelect, ProductCategorySelect},
  data() {
    return {
       rules: {
          name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
          ],
          outProductId: [
            { required: true, message: '请输入商品编码', trigger: 'blur' },
          ],
          categoryId: [
            { required: true, message: '请选择商品分类', trigger: ['blur', 'change'] },
          ],
          price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' },
          ],
          unit: [
            { required: true, message: '请输入商品单位', trigger: 'blur' },
          ],
          totalNum: [
            { required: true, message: '请输入商品库存', trigger: 'blur' },
          ],
          sort: [
            { required: true, message: '请输入商品排序', trigger: 'blur' },
          ],
          detailMobileHtml: [
            { required: true, message: '请输入商品详情页', trigger: 'blur' },
          ]
       },
      form: {
         categoryId: undefined,
         outProductId: undefined,
         name: '',
         pic: '',
         publishStatus: 0,
         sort: 1000,
         price: '',
         unit: '',
         totalNum: '',
         productChildList: [],
         detailMobileHtml: ''
      },
      skuAttr:[],
      albumPics:null,
      productAttr: [
        {
          name: '',
          options: [
            {name: '红'},
            {name: null}
          ]
        }
      ],
      maxOptionNum: 44
    }
  },
  created() {
    const {id} = this.$route.query
    if (id) {
      this.getInfo(id);
    }
  },
  methods: {
    refreshSku(){
      let skus = [];
      let skuMap = new Map()
      this.skuAttr=[...this.productAttr]
      if(this.form.skuList){
        this.form.skuList.forEach(sku=>{
          skuMap.set(sku.spData,sku)
        })
      }
      this.productAttr.forEach((attr, index) => {
        const attrSku = [];
        attr.options.forEach((option) => {
          if (!option.name) {
            return
          }
          if (index === 0) {
            attrSku.push({[attr.name]: option.name});
          } else {
            skus.forEach(it3 => {
              attrSku.push({...it3, [attr.name]: option.name })
            })
          }
        })
        skus = attrSku;
      })
      skus.forEach(it => {
        if(it){
          it.spData=JSON.stringify(it)
        }
      })
      skus.forEach(it => {
        let sku = skuMap.get(it.spData);
        if(sku){
          it.outSkuId = sku.outSkuId;
          it.price = sku.price;
          it.pic = sku.pic;
          it.stock = sku.stock;
          it.id = sku.id
        }else{
          it.outSkuId = null;
          it.price = null;
          it.pic = null;
          it.stock = null;
          it.id = null
        }

      })
      this.form.productAttr = JSON.stringify(this.productAttr)
      this.form.skuList= skus
    },
    categoryChange(value){

      console.log(value);
      if(Array.isArray(value.e)){
        console.log(value.e.toString())
        this.form.categoryId=value.e.toString()
      }else{
        this.form.categoryId=null
      }

    },
    onBrandChange(value){
      this.form.brandName = value
    },
    getInfo(id) {
      getPmsProduct(id).then(response => {
        const {albumPics } = response
        if (albumPics) {
          this.albumPics = albumPics.split(',')
        }
        this.form = response;
        if(this.form.productAttr){
          this.productAttr =JSON.parse(this.form.productAttr)
        }
        // this.refreshSku()
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // if(this.albumPics){
          //   this.form.albumPics = this.albumPics.toString()
          // }
          // if(this.form.categoryId && Array.isArray(this.form.categoryId)){
          //   this.form.categoryId = this.form.categoryId.pop()
          // }
          //商品价格没填时取sku的最低价
          // if (!this.form.price){
          //   this.form.price = Math.min.apply(Math, this.form.skuList.map(it => it.price))
          // }
          if (this.form.id != null) {
            updatePmsProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
            });
          } else {
            addPmsProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
            });
          }
          this.cancel();
        }else{
            this.$alert('请完善表单', '提示', {
              confirmButtonText: '确定',
            });
          // if(this.form.name){
          //   this.$alert('请填写规格价格', '提示', {
          //     confirmButtonText: '确定',
          //   });
          // }else{
          //   this.$alert('请填写商品名称', '提示', {
          //     confirmButtonText: '确定',
          //   });
          // }
        }
      });
    },
    cancel() {
      this.$tab.closeOpenPage({ path: '/pms/product' })
    },
    changeName(s, idx, val) {
      s.options[idx].name = val;
      if (s.options.length - 1 !== idx || s.options.length >= this.maxOptionNum) {
        return
      }
      s.options.push({name: null})
    },
    addSkuSort() {
      // this.productAttr.push({
      //   name: null,
      //   options: [{name: null}]
      // })
      this.form.productChildList.push({
        categoryId: this.form.categoryId,
        outProductId: '',
        name: '',
        pic: '',
        publishStatus: undefined,
        sort: 1000,
        price: '',
        unit: '',
        totalNum: '',
      })
    },
    deleteSkuSort(idx) {
      // this.productAttr.splice(idx);
      this.form.productChildList.splice(idx)
    },
    deleteOption(s, idx) {
      s.options.splice(idx, 1);
    }
  }
}
</script>

<style lang="stylus">
.add-product-wrapper
  padding 12px
  .content
    margin 0 auto
    width 75%
    min-width 800px
  .skus
      display: flex
      flex-direction: row
      margin-bottom: 22px
      .skus-label
        padding: 0 12px 0 0
        box-sizing: border-box
        line-height: 36px
        text-align: right
        width: 108px
        color: #606266
        font-weight: 600
        font-size: 14px
      .sku-wrapper
        width: calc(100% - 108px)
        background-color #f7f8fa
        padding 12px
        .sku_sorts
          .sku_sort
            background-color white
            margin-bottom 12px
            padding: 10px
            box-sizing: border-box
            .label
              padding 8px
            .values
              padding 8px 0 0 8px
              border-top 1px solid $border-color
              display flex
              flex-wrap wrap
              .value
                padding 0 32px 8px 0
                width 200px!important
                display flex
                align-items center
      .img-upload-mini .el-upload--picture-card
        width: 48px;
        height: 48px;
        line-height: 57px;
</style>
